"""
轻量级售出状态验证器 - 只检测连通性和售出状态，不提取详情和图片
"""
import re
from typing import List
from bs4 import BeautifulSoup

from axiom_boot.logging.setup import get_logger
from axiom_boot.scraper.interfaces import Extractor
from axiom_boot.scraper.models import Response, Target, Item

logger = get_logger(__name__)


class SoldVerificationItem(Item):
    """售出验证结果项"""
    ref_no: str
    is_sold: bool = False
    is_accessible: bool = True  # 页面是否可访问
    error_message: str = ""


class LightweightSoldVerifier(Extractor):
    """轻量级售出状态验证器 - 只检测售出状态，高性能"""

    def extract(self, response: Response, target: Target) -> List[Item]:
        """
        轻量级验证车辆售出状态
        
        Returns:
            List[SoldVerificationItem]: 验证结果
        """
        try:
            # 从URL中提取ref_no
            ref_no = self._extract_ref_no_from_url(response.url)
            
            # 检查页面是否可访问（简单检查）
            if not response.text or len(response.text) < 100:
                logger.debug(f"车辆 {ref_no} 页面内容过短，可能无法访问")
                return [SoldVerificationItem(
                    ref_no=ref_no, 
                    is_sold=True,  # 无法访问视为售出
                    is_accessible=False,
                    error_message="页面内容过短或无响应"
                )]
            
            soup = BeautifulSoup(response.text, "html.parser")
            
            # 检测售出状态
            is_sold = self._detect_sold_status(soup)
            
            logger.debug(f"车辆 {ref_no} 验证结果: 售出={is_sold}")
            
            return [SoldVerificationItem(
                ref_no=ref_no,
                is_sold=is_sold,
                is_accessible=True
            )]
            
        except Exception as e:
            ref_no = self._extract_ref_no_from_url(response.url)
            logger.warning(f"验证车辆 {ref_no} 售出状态失败: {e}")
            return [SoldVerificationItem(
                ref_no=ref_no,
                is_sold=False,  # 出错时保守处理，不标记为售出
                is_accessible=True,
                error_message=str(e)
            )]
    
    def _extract_ref_no_from_url(self, url: str) -> str:
        """从URL中提取ref_no"""
        try:
            match = re.search(r'refno=(\d+)', url)
            return match.group(1) if match else "unknown"
        except:
            return "unknown"
    
    def _detect_sold_status(self, soup: BeautifulSoup) -> bool:
        """
        检测售出状态 - 只检测关键标识
        
        Returns:
            bool: True表示已售出，False表示仍可售
        """
        try:
            # 主要检测: <img src="/images/stock/soldout.gif" id="soldout">
            soldout_img = soup.find('img', id='soldout')
            if soldout_img and 'soldout' in soldout_img.get('src', '').lower():
                logger.debug(f"发现soldout.gif图片，确认售出")
                return True
            
            # 备选检测: 其他可能的售出标识
            soldout_patterns = [
                {'tag': 'img', 'attrs': {'src': re.compile(r'soldout', re.I)}},
                {'tag': 'span', 'attrs': {'class': 'iconSold'}},
                {'tag': 'div', 'attrs': {'class': re.compile(r'sold', re.I)}}
            ]
            
            for pattern in soldout_patterns:
                element = soup.find(pattern['tag'], pattern['attrs'])
                if element:
                    logger.debug(f"发现售出标识: {pattern}")
                    return True
            
            # 检查页面标题或内容是否包含售出信息
            title = soup.find('title')
            if title and 'sold' in title.get_text().lower():
                logger.debug(f"页面标题包含sold信息")
                return True
            
            return False
            
        except Exception as e:
            logger.warning(f"检测售出状态时出错: {e}")
            return False  # 出错时保守处理
